package com.sairobo.live.util;

import com.sairobo.live.web.vo.response.BaseResponse;
import com.sairobo.live.web.vo.Constants;
import com.sairobo.live.web.vo.response.ResponseStatus;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.context.RequestContext;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问状态帮助类
 * <p>
 * Created by sdevil507 on 2017/4/29.
 */
public class AccessStateHelper {

    /**
     * 访问失败情况resp返回
     */
    public static void accessFailure401(RequestContext ctx,ResponseStatus responseStatus) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        ctx.getResponse().setCharacterEncoding("UTF-8");
        ctx.setResponseBody(JSON.toJSONString(AccessStateHelper.getBaseResponse(responseStatus)));
    }

    /**
     * token令牌校验通过执行转发请求,并将userId传递
     */
    public static void accessSuccess(RequestContext requestContext,String userID) {
        // 将userID通过header传送到具体应用
        requestContext.addZuulRequestHeader("userId", userID);
        requestContext.setSendZuulResponse(true);
    }

    public static BaseResponse getBaseResponse(ResponseStatus responseStatus) {
        BaseResponse baseResponse = new BaseResponse();
        if (responseStatus != null) {
            baseResponse.setMessage(responseStatus.getMessage());
            baseResponse.setCode(responseStatus.getCode());
            baseResponse.setData(Constants.NULL_DATA);
        }
        return baseResponse;
    }

    /**
     * 返回逻辑统一处理
     * @param ctx
     * @param responseStatus
     * @throws IOException
     */
    public static void responseHandler(RequestContext ctx, ResponseStatus responseStatus) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ctx.setSendZuulResponse(false);//zuul过滤请求，false为不路由，true为路由
        HttpServletResponse httpResponse = ctx.getResponse();
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.getWriter().write(mapper.writeValueAsString(AccessStateHelper.getBaseResponse(responseStatus)));
        ctx.setResponse(httpResponse);//返回response信息
    }

}
